package com.qs.javame.thread1028.test2;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class Test {

    public static void main(String[] args) {
        //阻塞队列，作为两个线程之间的公共资源，阻塞队列内置AQS可以保证线程安全，所以用阻塞队列实现生产者消费者，最合适不过了
        BlockingQueue<Res> blockingQueue = new ArrayBlockingQueue<>(1);

        //创建两个线程对象
        ProducerThread pro = new ProducerThread(blockingQueue);
        ConsumerThread con = new ConsumerThread(blockingQueue);

        //开启两个线程
        Thread proThread = new Thread(pro);
        Thread conThread = new Thread(con);
        proThread.start();
        conThread.start();

        //主线程
        try {
            Thread.sleep(1000);
            System.out.println("-->>主线程执行结束");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //优雅的关闭线程（线程任务执行完成，线程也就执行结束了）
        pro.shutdown();
        con.shutdown();
    }
}

class Res {

    private String sex;

    private String name;

    public Res(String sex, String name) {
        this.sex = sex;
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

/**
 * 定义生产者线程
 */
class ProducerThread implements Runnable {

    private BlockingQueue<Res> blockingQueue;

    private boolean flag = false;

    public ProducerThread(BlockingQueue<Res> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    @Override
    public void run() {
        int i = 0;
        while (!flag) {
            Res res = null;
            if (i % 2 == 0) {
                res = new Res("女", "小红");

            } else {
                res = new Res("男", "小军");
            }

            try {
                System.out.println("生产者：name=" + res.getName() + "，sex=" + res.getSex());
                //入队列
                blockingQueue.put(res);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            i++;
        }
    }

    //通过更改条件，结束线程任务
    public void shutdown(){
        this.flag = true;
    }
}

/**
 * 定义消费者线程
 */
class ConsumerThread implements Runnable {

    private BlockingQueue<Res> blockingQueue;

    private boolean flag = false;

    public ConsumerThread(BlockingQueue<Res> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    @Override
    public void run() {
        while (!flag) {
            try {
                Res res = blockingQueue.take();
                System.out.println("消费者：name=" + res.getName() + "，sex=" + res.getSex());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //通过更改条件，结束线程任务
    public void shutdown() {
        this.flag = true;
    }
}
